package com.iisigroup.selenium.common;


import com.iisigroup.screenshot.WebUtils;
import com.iisigroup.screenshot.constant.AppInfo;
import com.iisigroup.screenshot.constant.Level;
import com.iisigroup.screenshot.constant.SeleniumConfig;
import com.iisigroup.screenshot.constant.SystemId;
import com.thoughtworks.selenium.DefaultSelenium; 
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse; 
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.HasCapabilities;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter; 
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
 
/**
 * The Class SeleniumTestHelper.
 */
public class SeleniumTestHelper {

    
    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(SeleniumTestHelper.class);
     
    /** The Constant seleniumServerUrl. */
    private static final String seleniumServerUrl = "http://" + SeleniumConfig.getSeleniumServerHostName() + ":"
            + SeleniumConfig.getSeleniumServerPort() + "/";
     
    /**
     * Gets the base url.
     *
     * @param driver the driver
     * @return the base url
     * @throws MalformedURLException the malformed url exception
     */
    public  static URL getBaseUrl(final WebDriver driver) throws MalformedURLException{
        LOGGER.info("*** Starting selenium WebDriver ...");
        
     
        final Dimension targetSize = new Dimension(1500, 860);
        driver.manage().window().setSize(targetSize);
        //        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
        String regIp = WebUtils.getIpv4();
        
        //接下是要確認操控端與被空端是否為同一台機器？
        
        final String remoteNodIp = WebUtils.getIPOfNode((RemoteWebDriver) driver); 

        //列出準備要接受測試的ap 網址
        final AppInfo[] all =  AppInfo.values();
        
        
        for (AppInfo unit : all) {
            if (StringUtils.contains(remoteNodIp, unit.getPrefixPremoteIp())) { 
                //確認受控端與wb app 是否同一個網段？
                
                if (!(driver instanceof JavascriptExecutor)) {
                    throw new IllegalStateException("Driver instance must support JS.");
                }
                if (!((HasCapabilities) driver).getCapabilities().isJavascriptEnabled()) {
                    throw new IllegalStateException("JS support must be enabled.");
                }
                driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
                return new URL(unit.getAppUrl());
            }
        }
        final String baseUrl = String.format("http://%s:%s", SeleniumConfig.getSeleniumServerHostName(),SeleniumConfig.getSeleniumServerPort());
        return new URL(baseUrl);
    } 
   
   /**
    * Gets the base url.
    *
    * @param systemId the system id
    * @param level the level
    * @param driver the driver
    * @return the base url
    * @throws MalformedURLException the malformed url exception
    */
   public  static URL getBaseUrl(final SystemId systemId ,final Level level , final WebDriver driver)throws MalformedURLException{
       LOGGER.info("*** Starting selenium WebDriver ...");
       
    
       final Dimension targetSize = new Dimension(1500, 860);
       driver.manage().window().setSize(targetSize);
       //        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
       String regIp = WebUtils.getIpv4();
       
       //接下是要確認操控端與被空端是否為同一台機器？
       
       final String remoteNodIp = WebUtils.getIPOfNode((RemoteWebDriver) driver); 

       //列出準備要接受測試的ap 網址
       final AppInfo[] all =  AppInfo.values();
       
       
       for (AppInfo unit : all) {
           if (StringUtils.contains(remoteNodIp, unit.getPrefixPremoteIp())) { 
               //確認受控端與wb app 是否同一個網段？
               
               if (!(driver instanceof JavascriptExecutor)) {
                   throw new IllegalStateException("Driver instance must support JS.");
               }
               if (!((HasCapabilities) driver).getCapabilities().isJavascriptEnabled()) {
                   throw new IllegalStateException("JS support must be enabled.");
               }
               driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
               
               final String appPath = systemId.toString().toLowerCase()+level.toString().toLowerCase() ;
               
               if (AppInfo.UAT.equals(unit)){ 
                   final String RCTemplateURL = "http://%sc0c.ris.gov.tw:80/rc/";
                   final String RRTemplateURL ="http://%srfr.ris.gov.tw:80/rr/";
                   final  String RLTemplateURL ="http://%slfl.ris.gov.tw:80/rl/";
                   
                   //http://rc0c.ris.gov.tw/rc/    
                   //http://rrfr.ris.gov.tw/rr/
                   
                   switch (level) {
                   case C:
                      return new URL (String.format(RCTemplateURL ,systemId.toString().toLowerCase())); 
                   case R:
                       return new URL (String.format(RRTemplateURL ,systemId.toString().toLowerCase())); 
                   case L:
                       return new URL (String.format(RLTemplateURL ,systemId.toString().toLowerCase())); 
                   default:
                       break;
                   }
               }else{
                   final String port =  getSITPort(level) ;
                   return  new URL ( unit.getAppUrl(port , appPath));
               }
               // UAT("rlfl.ris.gov.tw","rl",80,"140");
               return  new URL (unit.getAppUrl() );
           }
       }
       final String baseUrl = String.format("http://%s:%s", SeleniumConfig.getSeleniumServerHostName(),SeleniumConfig.getSeleniumServerPort());
       return  new URL (baseUrl);
   } 
    
    /**
     * Gets the SIT port.
     *
     * @param level the level
     * @return the SIT port
     */
    private static  String getSITPort(final Level level) {
        String port = "";
        switch (level) {
        case C:
            port = "6180";
            break;
        case R:
            //新北市是6280,高雄是6180
            port = "6280";
            break;
        case L:
          //新北市是6280,高雄是6180
            port = "6280";
            break;
        default:
            break;
        }
        return port;
    }
    /**
     * Inits the web driver.
     *
     * @param driver the driver
     * @return the web driver backed selenium
     * @see "http://code.google.com/p/selenium/wiki/ChromeDriver"
     */
    public static WebDriverBackedSelenium initWebDriver(final WebDriver driver) {
        LOGGER.info("*** Starting selenium WebDriver ...");
       
        final Dimension targetSize = new Dimension(1500, 860);
        driver.manage().window().setSize(targetSize);
        //        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
         
        String regIp = WebUtils.getIpv4();
        
        //接下是要確認操控端與被空端是否為同一台機器？
        
        final String remoteNodIp = WebUtils.getIPOfNode((RemoteWebDriver) driver); 

        final AppInfo[] all =  AppInfo.values();
        for (AppInfo unit : all) {
            if (StringUtils.contains(remoteNodIp, unit.getPrefixPremoteIp())) {
                final WebDriverBackedSelenium selenium = new WebDriverBackedSelenium(driver, unit.getAppUrl());                
                return selenium;
            }
        }        
        return null;
    }

    /**
     * Destroy.
     *
     * @param selenium the selenium
     */
    public static void destroy(DefaultSelenium selenium) {
        LOGGER.info("*** Stopping selenium client driver ...");        
        selenium.stop();
    }

    /**
     * Extract object.
     *
     * @param resp the resp
     * @return the JSON object
     * @throws IOException Signals that an I/O exception has occurred.
     * @throws JSONException the JSON exception
     */
    private static JSONObject extractObject(HttpResponse resp) throws IOException, JSONException {
        InputStream contents = resp.getEntity().getContent();
        StringWriter writer = new StringWriter();
        IOUtils.copy(contents, writer, "UTF8");
        JSONObject objToReturn = new JSONObject(writer.toString());
        return objToReturn;
    }
}
